﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Taxonomy;
using Sukul.SharePoint.Taxomatic.Service;
using System.Xml;
using System.IO;

namespace Sukul.SharePoint.Taxomatic
{
    /// <summary>
    /// This class handles the request to download the taxonomy as an XML file and 
    /// also to upload the XML file to re-create the taxonomy
    /// </summary>
    /// <remarks>
    /// Author: Shailen Sukul
    /// Date: 17 Apr 2011
    /// </remarks>
    public class TaxomaticHandler : IHttpHandler
    {
        public bool IsReusable
        {
            get { return false; }
        }

        private string _SelectedTerms = string.Empty;
        private string _Mode = string.Empty;
        private void ExtractQueryString(HttpContext context)
        {
            _SelectedTerms = string.Empty;
            _Mode = string.Empty;
            if (!String.IsNullOrEmpty(context.Request.QueryString["terms"]))
            {
                _SelectedTerms = context.Request.QueryString["terms"];
            }
            if (!String.IsNullOrEmpty(context.Request.QueryString["mode"]))
            {
                _Mode = context.Request.QueryString["mode"];
            }
        }
        public void ProcessRequest(HttpContext context)
        {
            ExtractQueryString(context);
            //context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            //context.Response.Cache.SetNoStore();
            //context.Response.Cache.SetExpires(DateTime.MinValue);

            switch (_Mode.ToLower())
            {
                case "export":
                    Export(context);
                    break;
                case "import":
                    Import(context);
                    break;
                default:
                    About(context);
                    break;
            }
        }

        private void Import(HttpContext context)
        {
            try
            {
                if (context.Request.Files.Count == 0)
                {
                    //context.Response.ContentType = "text/plain";
                    //context.Response.Write("Upload file was not specified.");

                    //Internal Server Error            
                    context.Response.StatusCode = 500;
                    context.Response.End();
                }
                var strExtension = Path.GetExtension(context.Request.Files[0].FileName).ToLower();
                if (strExtension == "xml")
                {
                    //context.Response.ContentType = "text/plain";
                    //context.Response.Write("The file must be an xml file.");
                    //Internal Server Error            
                    context.Response.StatusCode = 500;
                    context.Response.End();
                }

                StreamReader sr = new StreamReader(context.Request.Files[0].InputStream);
                TaxonomyHelper.Instance.ImportTaxonomy(sr.ReadToEnd());
            }
            catch
            {
                //Internal Server Error            
                context.Response.StatusCode = 500;
                context.Response.End();
            }
        }

        private void Export(HttpContext context)
        {
            try
            {
                context.Response.Headers.Add("Content-Disposition", "attachment;filename=Taxomatic.Export.xml");
                context.Response.ContentType = "application/xml";
                context.Response.Write(TaxonomyHelper.Instance.ExportTaxonomy());
            }
            catch
            {
                //Internal Server Error            
                context.Response.StatusCode = 500;
                context.Response.End();
                // context.Response.Write(ex.ToString());
            }
        }

        private void About(HttpContext context)
        {
            context.Response.ContentType = "text/html";
            context.Response.Write(string.Format(@"<b>Taxomatic</b>{0}<p>This utility allows you to browse, export and import SharePoint taxonomy</p>", @"<br/>"));
        }
        private int HarvestCurrentLCID(System.Web.HttpContext context)
        {
            return (int)Microsoft.SharePoint.WebControls.SPControl.GetContextWeb(context).Language;
        }
    }
}
